package com.example.baseweather.ui;

import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;

import com.example.baseweather.MainActivity;
import com.example.baseweather.MyApplication;
import com.example.baseweather.R;
import com.example.baseweather.databinding.ActivityVideoPlayBinding;
import com.example.baseweather.databinding.PopVideoInfoBinding;
import com.example.baseweather.domain.VideoInfoBean;
import com.example.baseweather.utils.CommonUtils;

import java.io.File;
import java.util.concurrent.TimeUnit;

public class VideoPlayActivity extends AppCompatActivity implements SurfaceHolder.Callback {

    private ActivityVideoPlayBinding binding;
    private MediaPlayer mediaPlayer;
    private SurfaceHolder surfaceHolder;
    private PopVideoInfoBinding popVideoInfoBinding;
    private PopupWindow popupWindow;

    Runnable updateProgressTask = new Runnable() {
        @Override
        public void run() {
            MyApplication.getHandler().post(() -> {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    int currentPosition = mediaPlayer.getCurrentPosition();
                    binding.tvCurrentProgress.setText(CommonUtils.formatDate(currentPosition) + "/");
                    binding.seekBar.setProgress(currentPosition, true);
                }
            });
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityVideoPlayBinding.inflate(getLayoutInflater());
        popVideoInfoBinding = PopVideoInfoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        CommonUtils.showFullScreen(this, binding.getRoot());
        initView();
    }

    private void initView() {
        surfaceHolder = binding.surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        initPopWindowView();
        binding.btnAnother.setOnClickListener(v -> {
            popupWindow.showAsDropDown(v, 0, -240, Gravity.TOP);
        });
        binding.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mediaPlayer != null) {
                    int progress = seekBar.getProgress();
                    mediaPlayer.seekTo(progress);
                }
            }
        });


        binding.ivPlayControl.setOnClickListener(v -> {
            //运行状态
            ImageView view = (ImageView) v;
            if (view.getTag() == "resume") {
                view.setImageResource(R.drawable.iv_pause);
                view.setTag("pause");
                mediaPlayer.pause();
            } else {
                //停止状态
                view.setImageResource(R.drawable.iv_resume);
                view.setTag("resume");
                mediaPlayer.start();
            }
        });

        binding.ivNext.setOnClickListener(v -> {
            int currentPosition = mediaPlayer.getCurrentPosition();
            int wholeDuration = mediaPlayer.getDuration();
            if (currentPosition == wholeDuration) {
                CommonUtils.showToastShort("当前已到视频结尾", this);
            } else if (currentPosition + 3000 > wholeDuration) {
                mediaPlayer.seekTo(wholeDuration);
            } else {
                mediaPlayer.seekTo(currentPosition + 3000);
            }
        });

        binding.ivPre.setOnClickListener(v -> {
            int currentPosition = mediaPlayer.getCurrentPosition();
            mediaPlayer.seekTo(currentPosition < 3000 ? 0 : currentPosition - 3000);
        });


        binding.ivBack.setOnClickListener(v->{
            onBackPressed();
        });
    }

    private void initPopWindowView() {
        File[] videoPath = CommonUtils.getVideoPath();
        for (File file : videoPath) {
            VideoInfoBean videoInfo = CommonUtils.getVideoInfo(file);
            TextView textView = new TextView(this);
            textView.setTextSize(20);
            textView.setBackgroundColor(Color.WHITE);
            textView.setPadding(8, 8, 8, 8);
            LinearLayoutCompat.LayoutParams layoutParams =
                    new LinearLayoutCompat.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT,
                            LinearLayoutCompat.LayoutParams.WRAP_CONTENT);
            textView.setLayoutParams(layoutParams);
            textView.setText(videoInfo.getVideoName() + ".mp4");
            popVideoInfoBinding.lnContainer.addView(textView);
        }
        popupWindow = new PopupWindow(this);
        popupWindow.setContentView(popVideoInfoBinding.getRoot());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Integer integer = MainActivity.map.get(getPackageName() + "video");
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(this, Uri.fromFile(CommonUtils.getVideoPath()[integer])); // Replace with your video URL
            mediaPlayer.setDisplay(surfaceHolder);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(mp -> {
                mediaPlayer.start();
                int duration = mediaPlayer.getDuration();
                binding.seekBar.setMax(duration);
                String timeString = CommonUtils.formatDate(duration);
                binding.tvWholeProgress.setText(timeString);
                MyApplication.getExecutorService().scheduleAtFixedRate(updateProgressTask
                        , 0, 1, TimeUnit.SECONDS);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // Handle surface changes if necessary
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }


}
